package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.MD5Util;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.dao.KwAydPushDao;
import com.meirengu.webview.model.KwAydPush;
import com.meirengu.webview.model.KwAydPushLog;
import com.meirengu.webview.service.KwAydPushLogService;
import com.meirengu.webview.service.KwAydPushService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.meirengu.common.StatusCode.OK;
import static com.meirengu.utils.UuidUtils.uuid;
import static com.meirengu.webview.common.Constants.*;
import static com.meirengu.webview.service.impl.KwAydFilterServiceImpl.HUIJIE_CHANNEL_CODE;
import static com.meirengu.webview.service.impl.KwAydFilterServiceImpl.HUIJIE_CHANNEL_NAME;
import static org.apache.commons.lang3.StringUtils.isEmpty;

/**
 * KwAydPush服务实现层
 *
 * @author Mao
 * @create Wed May 09 11:15:43 CST 2018
 */
@Service
public class KwAydPushServiceImpl extends BaseServiceImpl<KwAydPush> implements KwAydPushService {


    @Autowired
    private KwAydPushLogService kwAydPushLogService;

    @Autowired
    private KwAydPushDao kwAydPushDao;


    Logger logger = LoggerFactory.getLogger(KwAydPushServiceImpl.class);


    public int updateSuccess(String id) {
        return kwAydPushDao.updateSuccess(id);
    }


    @Override
    public Integer sendShanjie(String name, String mobile, String city, String car, Integer age,
                               String job, String house, String baodan_is, String sex, Integer money,
                               String shebao, String gongjijin, String isbankpay) throws Exception {

        String url = ConfigUtil.getConfig("shanjie.url");
        String source = ConfigUtil.getConfig("shanjie.source");
        String now = String.valueOf(new Date().getTime());
        now = now.substring(0, 10);
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("name", name);
        parameters.put("mobile", mobile);
        parameters.put("city", city);
        parameters.put("car", car);
        parameters.put("age", age + "");
        parameters.put("job", job);
        parameters.put("house", house);
        parameters.put("baodan_is", baodan_is);
        parameters.put("sex", sex);
        parameters.put("money", money + "");
        parameters.put("source", source);
        parameters.put("shebao", shebao);
        parameters.put("gongjijin", gongjijin);
        parameters.put("isbankpay", isbankpay);
        parameters.put("time", now);


        //接口调用信息表
        KwAydPush kwAydPush = new KwAydPush();
        kwAydPush.setInterfaceCode("shanjie");
        kwAydPush.setInterfaceName("闪借");
        kwAydPush.setMobile(mobile);
        kwAydPush.setCode(BUSINESS_STATUS_FAIL);

        KwAydPushLog kwAydPushLog = new KwAydPushLog();
        kwAydPushLog.setInterfaceCode("shanjie");
        kwAydPushLog.setInterfaceName("闪借");
        kwAydPushLog.setMobile(mobile);
        kwAydPushLog.setSendUrl(url.toString());
        kwAydPushLog.setParams(parameters.toString());

        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPostForm(url.toString(), parameters);
            int code = hr.getStatusCode();
            if (code == 200) {
                kwAydPushLog.setBackUrl(hr.toString());
                kwAydPushLog.setHttpCode(200);
                kwAydPushLog.setHttpContent(hr.toString());

                logger.info("==KwAydPushServiceImpl.sendShanjie request success. result:{}", hr.toString());
                String content = hr.getContent();
                if ("3".equals(content)) {
                    kwAydPush.setCode(BUSINESS_STATUS_OTHER);
                    kwAydPush.setMessage(hr.toString());
                    logger.info("==KwAydPushServiceImpl.sendShanjie business fail");
                } else if ("5".equals(content)) {
                    kwAydPush.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    kwAydPush.setMessage(hr.toString());
                    logger.warn("==KwAydPushServiceImpl.sendShanjie business fail");
                } else if ("6".equals(content)) {
                    kwAydPush.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    kwAydPush.setMessage(hr.toString());
                    logger.warn("==KwAydPushServiceImpl.sendShanjie business fail");
                } else if ("7".equals(content)) {
                    kwAydPush.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    kwAydPush.setMessage(hr.toString());
                    logger.warn("==KwAydPushServiceImpl.sendShanjie business fail");
                } else {
                    kwAydPush.setCode(BUSINESS_STATUS_SUCCESS);
                    kwAydPush.setMessage(hr.toString());
                    logger.warn("==KwAydPushServiceImpl.sendShanjie business success");
                }
            } else {
                kwAydPushLog.setBackUrl(hr.toString());
                kwAydPushLog.setHttpCode(code);
                kwAydPushLog.setHttpContent(hr.toString());
                logger.warn("==KwAydPushServiceImpl.sendShanjie request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwAydPushLog.setHttpCode(408);
            kwAydPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwAydPush);
            kwAydPushLog.setPushId(kwAydPush.getId());
            kwAydPushLogService.insert(kwAydPushLog);
            return kwAydPush.getCode();
        }
    }


    /**
     * 创建sign
     * name + phone + channel后MD5加密，转为大写字母
     */
    private String createSign(String name, String mobile, String channel) {
        return MD5Util.md5Hex(name + mobile + channel).toUpperCase();
    }



    private String createSign(String bizStr, String secret) throws UnsupportedEncodingException {
        String firstMd5 = getMD5(bizStr.getBytes("UTF-8"));
        String hmacStr = HmacUtils.hmacSha256Hex(secret, firstMd5);
        return getMD5(hmacStr.getBytes());
    }

    private String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[(byte0 >>> 4) & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return s;
    }

}
